package com.zy.study.controller;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.http.impl.conn.ConnectionShutdownException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zy.study.pojo.CountryData;
import com.zy.study.service.GetDataService;
import com.zy.study.utils.ResponseCode;
import com.zy.study.utils.ServiceResponse;
import com.zy.study.utils.MyException.BizException;

import lombok.Data;

@Data
@RestController
public class GetDataController {
	@Autowired
	private GetDataService getDataService;

	@RequestMapping("/getTopFiveDataByUrl")
	public ServiceResponse getTopFiveDataByUrl() throws Exception {
		
		//数据接口URL
		String dataSourceUrlString = "https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=1582418617382";
		
		//得到返回的数据列表
		List<CountryData> allWorldData = getDataService.getDataListByUrl(dataSourceUrlString);
		
		if (allWorldData == null) {
			
			return ServiceResponse.createByErrorMessage("未查询到任何数据");
			
		} else {
			
			//排序
			List<CountryData> allSortData = allWorldData.stream()
					.sorted(Comparator.comparing(CountryData::getCumulativeComfirmed)).collect(Collectors.toList());
			
			//全世界感染的总人数
			int allWorldConfirm = 0;
			
			//全世界死亡的人数
			int allWorldDead = 0;
			
			for (int i = 0; i < allSortData.size(); i++) {
				
				allWorldConfirm += allSortData.get(i).getCumulativeComfirmed();
				
				allWorldDead += allSortData.get(i).getDeathTotal();
				
			}
			
			//得到确诊人数前五的国家数据对象
			List<CountryData> topFiveData = allSortData.subList(allSortData.size() - 5, allSortData.size());
			
			Collections.reverse(topFiveData);
			
			//百分比的格式
			NumberFormat numberFormat = NumberFormat.getInstance();
			
			// 设置精确到小数点后2位
			numberFormat.setMaximumFractionDigits(2);
			
			for (int i = 0; i < topFiveData.size(); i++) {
				
				//设置感染的百分比
				topFiveData.get(i).setPercentOfConfirmed(numberFormat
						.format((float) topFiveData.get(i).getCumulativeComfirmed() / (float) allWorldConfirm * 100));
				
				//设置死亡的百分比
				topFiveData.get(i).setPercentOfDead(
						numberFormat.format((float) topFiveData.get(i).getDeathTotal() / (float) allWorldDead * 100));

			}
			
			return ServiceResponse.createBySuccess(topFiveData);
			
		}
	}

	@RequestMapping("/testException")
	public ServiceResponse<String> testException() {
		
		if (1 == 1) {
			
			throw new BizException(ResponseCode.PARAM_PARAMETER_ERROR.getCode(), "用户姓名不能为空！");
			
		}
		
		return ServiceResponse.createByError();
	}
}
